package com.hongxun.modules.eys.controller;

import com.hongxun.common.utils.R;
import com.hongxun.modules.api.entity.BDataDictionaryEntity;
import com.hongxun.modules.api.entity.BMaterialEntity;
import com.hongxun.modules.bss.entity.*;
import com.hongxun.modules.bss.service.*;
import com.hongxun.modules.csg.entity.dxf.WordUtil;
import com.hongxun.modules.csg.tools.DxfUtil;
import com.hongxun.modules.csg.tools.StringUtil;
import com.hongxun.modules.eys.entity.*;
import com.hongxun.modules.eys.service.*;
import com.hongxun.modules.sys.controller.AbstractController;
import com.hongxun.modules.sys.entity.SysDeptEntity;
import com.hongxun.modules.sys.service.SysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.DecimalFormat;
import java.util.*;

/**
 * DXF文件导出Controller
 *
 * Created by john on 2018/11/26.
 */
@RestController
@RequestMapping("/eys/ePBaseLineArea")
public class EPBaseLineAreaController extends AbstractController {

    @Autowired
    private EPBaseService ePBaseService;
    @Autowired
    private SysDeptService sysDeptService;
    @Autowired
    private EPointService ePointService;
    @Autowired
    private EDrawLineService eDrawLineService;
    @Autowired
    private ECrossCostService eCrossCostService;
    @Autowired
    private EDeviceBuyService eDeviceBuyService;
    @Autowired
    private EPWireService ePWireService;




    /**
     *  导出DXF文件
     *
     * @param request
     * @param response
     * DXF导出需要改到项目储备和施工中去
     */
    @RequestMapping(value = "/expDxfFile")
    public void expDxfFile(HttpServletRequest request, HttpServletResponse response) {
        response.setCharacterEncoding("utf-8");
        try {
            String template = "dxf2007_test.ftl";	//模板名称
            String namss=request.getParameter("svgStr").replace("@#@","<")
                    .replace("$#$",">");//对HTML标签进行反转义

            // 生成DXF文件所需组码
            Map<String, Object> result = DxfUtil.svgToDxfData(namss);
            String fileOnlyName = System.currentTimeMillis() + ".dxf";

            String dxf_file_name = request.getParameter("dxf_file_name");//文件名
            if (StringUtil.isNotEmpty(dxf_file_name)) {
                fileOnlyName = dxf_file_name + ".dxf";
            }
            // 存放路径
            String filePath = "D:\\budgetDXF\\foundation";
            //生成Excel
            String url = WordUtil.createWord(result, template, filePath, fileOnlyName);
            if (StringUtil.isNotEmpty(url)) {
                File file = new File(url);
                //得到文件名
                String filename = file.getName();
                //如果文件不存在会抛出FileNotFoundException异常，需要捕获后进行处理
                InputStream fis = new BufferedInputStream(new FileInputStream(url));
                byte[] buffer = new byte[fis.available()];
                fis.read(buffer);
                fis.close();
                //清空response
                response.reset();
                String downLoadName = new String(filename.getBytes("gbk"), "iso8859-1");
                // 设置response的Header
                response.addHeader("Content-Disposition", "attachment;filename=" + downLoadName);
                response.addHeader("Content-Length", "" + file.length());
                OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
                response.setContentType("application/octet-stream");
                toClient.write(buffer);
                toClient.flush();
                toClient.close();
            } else {
                response.setContentType("text/html");
                try {
                    response.getWriter().print("<html><body><h1>生成dxf文档失败，请刷新后重试！</h1></body></html>");
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        } catch (Exception e) {
            //log.error(e.getMessage(), e);
            e.printStackTrace();
            response.setContentType("text/html");
            try {
                response.getWriter().print("<html><body><h1>生成dxf文档失败，请刷新后重试！</h1></body></html>");
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }


    /**
     * 项目信息组装
     *
     * @param pGuid
     * @return
     * @Time 2018-11-15 16:55:01 修改
     */
    public String getProInfoOnCad(String pGuid , String LineArea){

        StringBuffer sBuff = new StringBuffer();
        List<EPointEntity> list_DPoint_10kv = null;
        List<EPointEntity> list_DPoint_all = null;
        List<EPBaseEntity> list_CPBase_10kv = null;
        List<BMaterialEntity> list_BMater = null;

        Map<String , Object> c_10kv_Map = new HashMap<>();
        Map<String , Object> c_all_Map = new HashMap<>();
        DecimalFormat df = new DecimalFormat("######0.000");

        //所有线路
        String c_all = " 1=1 and p_guid='"+pGuid+"' and p_p_worktype='新增' ";
        //台区
        if(LineArea != null  && !LineArea.equals("")){
            c_all += " and p_r_guid='"+LineArea+"'";
        }
        c_all_Map.put("filterSql",c_all);
        list_DPoint_all = ePointService.queryList(c_all_Map);


		/*  10kv线路导线长度、材料及类型 */
        String c_10kv = " 1=1 and p_guid='"+pGuid+"' and p_p_voltage= '1' and p_p_worktype='新增' ";
        //台区
        if(LineArea != null && !LineArea.equals("")){
            c_10kv += " and p_r_guid='"+LineArea+"'";
        }
        c_10kv_Map.put("filterSql",c_10kv);
        list_DPoint_10kv = ePointService.queryList(c_10kv_Map);

        String info_10kv = "";
        String where_10kv = " 1=1 ";
        Map<String , Object> map_10kv = new HashMap<>();
        double total_line_length = 0;	//线路总长度
        double line_length_10kv = 0;	//10kv线路长度
        double sum_10kv = 0;

        if (list_DPoint_10kv != null) {
            List<String> list11 = new ArrayList<>();
            for (int i = 0; i < list_DPoint_10kv.size(); i++) {
                // 计算线路长度
                EPointEntity ePointEntity = list_DPoint_10kv.get(i);
                if (ePointEntity.getPPAutospan() == null || ePointEntity.getPPAutospan().toString().equals("0.00")){//档距为空或者为0的情况，
                    line_length_10kv = 0;
                }else{//档距不为空且不为0时
                    double span = Double.parseDouble(ePointEntity.getPPAutospan().toString());
                    total_line_length += span;
                    line_length_10kv += span;
                    sum_10kv += span;
                }
                //选出导线材料ID
                if(ePointEntity.getPWGuid() != null){
                    list11.add(ePointEntity.getPWGuid());
                }

            }
            // 导线材料及类型
            List<String > list_10 = removeDuplicate(list11);
            for (String s : list_10) {
                where_10kv += " and p_m_guid='"+s+"'";
                map_10kv.put("filterSql",where_10kv);
                List<EPWireEntity> bm = ePWireService.queryList(map_10kv);
                for (EPWireEntity dMater : bm) {
                    info_10kv += dMater.getPWName() + "线型" + df.format(sum_10kv / 1000) + "km";
                }
                info_10kv += "、";
            }
        }
        info_10kv = removeDunhao(info_10kv);
        info_10kv = info_10kv.substring(info_10kv.indexOf("，")+1,info_10kv.length());



		/*  0.38kv线路导线长度、材料及类型 *********/
        List<EPointEntity> list_DPoint_380v = null;
        List<EPBaseEntity> list_CPBase_380v = null;
        List<BMaterialEntity> list_BMater_380v = null;
        Map<String , Object> c_380v_Map = new HashMap<>();
        String c_380v = " 1=1 and p_guid='"+pGuid+"' and p_p_voltage= '2' and p_p_worktype='新增' ";
        //台区
        if(LineArea != null && !LineArea.equals("")){
            c_380v += " and p_r_guid='"+LineArea+"'";
        }
        c_380v_Map.put("filterSql",c_380v);
        list_DPoint_380v = ePointService.queryList(c_380v_Map);

        String info_380v = "";
        String where_380v = " 1=1 ";
        Map<String , Object> map_380v = new HashMap<>();
        double line_length_380v = 0;	//380v线路长度
        double sum_380v = 0;
        if (list_DPoint_380v != null) {
            List<String> list22 = new ArrayList<>();
            for (EPointEntity ePointEntity : list_DPoint_380v) {
                // 计算长度
                if(ePointEntity.getPPAutospan() ==null || ePointEntity.getPPAutospan().toString().equals("0.00")){//档距为空或者为0时
                    line_length_380v = 0;
                }else{//档距不为空且不为0时
                    double span = Double.parseDouble(ePointEntity.getPPAutospan().toString());
                    total_line_length += span;
                    line_length_380v += span;
                    sum_380v += span;
                }
                //导线材料ID
                if(ePointEntity.getPWGuid() != null){
                    list22.add(ePointEntity.getPWGuid());
                }
            }
            // 导线材料及型号
            List<String> list_380 = removeDuplicate(list22);
            for (String s : list_380) {
                where_380v += " and p_m_guid='"+s+"'";
                map_380v.put("filterSql",where_380v);
                List<EPWireEntity> bm = ePWireService.queryList(map_380v);

                for (EPWireEntity dMater : bm) {
                    info_380v += dMater.getPWName()+ "线型" +df.format(sum_380v / 1000)+ "km";
                }
                info_380v += "、";
            }

        }
        info_380v = removeDunhao(info_380v);
        info_380v = info_380v.substring(info_380v.indexOf("，")+1,info_380v.length());



		/*  0.22kv线路导线长度、材料及类型 *********/
        List<EPointEntity> list_DPoint_220v = null;
        List<EPBaseEntity> list_CPBase_220v = null;
        List<BMaterialEntity> list_BMater_220v = null;
        Map<String , Object> c_220v_Map = new HashMap<>();
        String c_220v = " 1=1 and p_guid='"+pGuid+"' and p_p_voltage= '3' and p_p_worktype='新增' ";
        //台区
        if(LineArea != null && !LineArea.equals("")){
            c_220v += " and p_r_guid='"+LineArea+"'";
        }
        c_220v_Map.put("filterSql",c_220v);
        list_DPoint_220v = ePointService.queryList(c_220v_Map);

        String info_220v = "";
        String where_220v = " 1=1 ";
        Map<String , Object> map_220v = new HashMap<>();
        double line_length_220v = 0;	//10kv线路长度
        double sum_220v = 0;
        if (list_DPoint_220v != null) {
            List<String> list33 = new ArrayList<>();
            for (EPointEntity ePointEntity : list_DPoint_220v) {
                //导线长度
                if(ePointEntity.getPPAutospan() == null || ePointEntity.getPPAutospan().toString().equals("0.00")){//档距为空或者为0时
                    line_length_220v = 0;
                }else{//档距不为空且不为0时
                    double span = Double.parseDouble(ePointEntity.getPPAutospan().toString());
                    total_line_length += span;
                    line_length_220v += span;
                    sum_220v += span;
                }
                //导线材料ID
                if(ePointEntity.getPWGuid() != null){
                    list33.add(ePointEntity.getPWGuid());
                }
            }
            //导线材料及类型
            List<String> list_220 = removeDuplicate(list33);
            for (String s : list_220) {
                where_220v += " and p_m_guid='"+s+"'";
                map_220v.put("filterSql",where_220v);
                List<EPWireEntity> bm = ePWireService.queryList(map_220v);

                for (EPWireEntity dMater : bm) {
                    info_220v += dMater.getPWName() + "线型" + df.format(sum_220v / 1000) + "km";
                }
                info_220v += "、";
            }
        }
        info_220v = removeDunhao(info_220v);
        info_220v = info_220v.substring(info_220v.indexOf("，")+1,info_220v.length());



		/*    信息组装 ******/
        if (total_line_length == 0) {
            sBuff.append("1、本工程线路总长" + df.format(total_line_length / 1000) + "km。");
        } else {
            sBuff.append("1、本工程线路总长" + df.format(total_line_length / 1000) + "km，其中");
            if (info_10kv!=null && !info_10kv.equals("")) {
                sBuff.append("10kV线路" + df.format(sum_10kv / 1000) + "km，" + info_10kv);
                if ((info_380v!=null && !info_380v.equals("")) || (info_220v!=null && !info_220v.equals(""))) {
                    sBuff.append("；");
                }
            }
            if (info_380v!=null && !info_380v.equals("")) {
                sBuff.append("0.4kV线路" + df.format(sum_380v / 1000) + "km，" + info_380v);
                if (info_220v!=null && !info_220v.equals("")) {
                    sBuff.append("；");
                }
            }
            if (info_220v!=null && !info_220v.equals("")) {
                sBuff.append("0.22kV线路" + df.format(sum_220v / 1000) + "km，" + info_220v);
            }
            sBuff.append("。");
        }


        //杆塔
        List<BDataDictionaryEntity> bdlist = new ArrayList<>();
        Map<String ,Object> bdMap = new HashMap<>();
        String str = "";
        String s1 = "";
        int poleTotal = 0;
        int alld_point = 0;
        String where_pole = " 1=1 ";
        Map<String , Object> map_pole = new HashMap<>();
        List<String> list44 = new ArrayList<>();
        if (list_DPoint_all != null) {
            for (EPointEntity ePointEntity : list_DPoint_all) {
                if(ePointEntity.getPPName().equals("杆塔")) {
                    // 计算杆塔基数
                    poleTotal += 1;
                    // 获取杆高
                    list44.add(ePointEntity.getPPBar().toString());
                }
            }
            // 获取杆高及基数(去重)
            List<String> list_pole = removeDuplicate(list44);
            for (String s : list_pole) {
                where_pole = " and p_p_worktype = '新增' AND p_p_datastate != '删除' and p_p_name='杆塔' and p_p_bar='"+s+"' and p_guid='"+pGuid+"'";
                //台区
                if(LineArea != null && !LineArea.equals("")){
                    where_pole += " and p_r_guid='"+LineArea+"'";
                }
                map_pole.put("filterSql",where_pole);
                Integer pole_pbar = ePointService.queryTotal(map_pole);
                s = s.substring(0,s.indexOf("."));
                str = s+"米"+pole_pbar+"基"+"、"+str;
            }
        }
        str = removeDunhao(str);//去除末尾顿号
        if (poleTotal == 0) {
            sBuff.append("2、本工程杆塔" + poleTotal + "基；");
        } else {
            sBuff.append("2、本工程杆塔" + poleTotal + "基，" + str + "；");
        }


        //变压器
        List<BDataDictionaryEntity> bylist = new ArrayList<>();
        Map<String ,Object> byMap = new HashMap<>();
        String str22 = "";
        int transTotal = 0;
        int alld_point1 = 0;
        String where_T = " 1=1 ";
        Map<String , Object> map_T = new HashMap<>();
        List<String> list55 = new ArrayList<>();
        boolean tr = false ;
        if (list_DPoint_all != null) {
            for (EPointEntity ePointEntity : list_DPoint_all) {
                if(ePointEntity.getPPName().equals("柱上变压器")) {
//					alld_point1 +=1;
                    // 获取点位ID
                    list55.add(ePointEntity.getGuid());
                    tr = true;
                }
            }
            if(tr) {
                List<String> list_Tt = removeDuplicate(list55);//去重
                List<String> list_dev = new ArrayList<>();
                for (String s : list_Tt) {
                    // 点位设备表查询
                    where_T = " and p_p_guid='" + s + "' and d_b_bigtype='变压器' and d_b_datastate !='删除' ";
                    map_T.put("filterSql", where_T);
                    List<EDeviceBuyEntity> DDeviceList = eDeviceBuyService.queryList(map_T);
                    for (EDeviceBuyEntity dDev : DDeviceList) {
                        list_dev.add(dDev.getDLabel());
                    }
                }
                //变压器型号及数量
                List<String> list_ss = removeDuplicate(list_dev);//去重
                String where_Num = " 1=1 ";
                Map<String, Object> map_Num = new HashMap<>();
                for (String s2 : list_ss) {
                    where_Num = " and d_label='" + s2 + "' and p_guid='" + pGuid + "' AND d_b_bigtype='变压器' AND d_label ='" + s2 + "'";
                    map_Num.put("filterSql", where_Num);
                    int _Num = eDeviceBuyService.queryTotal(map_Num);
                    alld_point1 = _Num;
                    str22 += s2 + "型变压器" + alld_point1 + "台" + "、" + str22;
                }

                str22 = removeDunhao(str22);
                if(!str22.equals("")) {
                    if(str22.lastIndexOf("、") != -1) {
                        str22 = str22.substring(0, str22.lastIndexOf("、"));
                        sBuff.append(str22 + "。");
                    }else{
                        sBuff.append(str22 + "。");
                    }
                }
            }
        }else {
            sBuff.append("设备类别-设备容量变压器0台。");
        }


        //交叉跨越
        List<ECrossCostEntity> list_dcross = new ArrayList<>();
        Map<String , Object> crossMap = new HashMap<>();
        String crossWhere = " 1=1 and p_guid='"+pGuid+"' and c_c_datastate != '删除' ";
        //台区
        if(LineArea != null && !LineArea.equals("")){
            crossWhere += " and p_r_guid='"+LineArea+"'";
        }
        crossMap.put("filterSql",crossWhere);
        list_dcross = eCrossCostService.queryList(crossMap);
        String cross_info = "";
        if (list_dcross.size()>0) {
            sBuff.append("3、交叉跨越：");
            crossMap.clear();
            int aa = 0 ;
            for (ECrossCostEntity listDcross : list_dcross) {

                String cross_1 = " 1=1 and p_guid='"+pGuid+"' and c_c_name='"+listDcross.getCCName()+"' and c_c_datastate != '删除' ";
                //台区
                if(LineArea != null && !LineArea.equals("")){
                    cross_1 += " and p_r_guid='"+LineArea+"'";
                }
                crossMap.put("filterSql",cross_1);
                aa = eCrossCostService.queryTotal(crossMap);
//                sBuff.append(listDcross.getCCName() + "" + aa + "处");
                cross_info  = listDcross.getCCName() + "" + aa + "处"+"、"+cross_info;
            }
            cross_info = removeDunhao(cross_info);
//            cross_info = cross_info.substring(0, cross_info.lastIndexOf("、"));
            sBuff.append(cross_info+"。");
        }else {
            sBuff.append("3、交叉跨越0处。");
        }

        return sBuff.toString();
    }


    /**
     * 获取所有点位信息
     * @param pGuid		项目ID
     * @param LineArea	线路台区
     * @return
     * @addTime 2018-10-17 11:31:54
     */
    @RequestMapping("getAllPointInfo")
    public R getAllPointInfo(String pGuid , String LineArea){

        // TODO: 2018/11/23  p_r_guid 所属项目范围ID ，就是台区ID，需要点位表d_point联合项目范围表a_p_range
        // 点位表中的p_r_guid和交叉跨越表中的p_r_guid都是所属项目范围ID（线路台区ID），和项目范围表a_p_range进行关联

        //组装数据
        List list = new ArrayList();
        List<EPointEntity> pointList = new ArrayList<>();
        List<EDrawLineEntity> laxList = new ArrayList<>();
        List<EDrawLineEntity> laxianList = new ArrayList<>();
        List<ECrossCostEntity> dCrossList = new ArrayList<>();
        List<ECrossCostEntity> dCrossCostList = new ArrayList<>();
        Map<String , Object> pointMap = new HashMap<>();
//		String pGuid = params.get("pGuid").toString();//项目ID

        //1.根据项目ID获取点位信息
        String pointWhere = " 1=1 and p_guid='"+pGuid+"' and p_p_worktype='新增' and p_p_datastate != '删除' ";
        //台区选择
        if(LineArea != null && !LineArea.equals("")){
            pointWhere += " and p_r_guid='"+LineArea+"'";
        }
        pointMap.put("filterSql", pointWhere);
        pointList = ePointService.queryList(pointMap);


        //2.根据点位获取拉线信息
        for (EPointEntity ePointEntity : pointList) {

            //杆塔拉线
            pointMap.clear();
            if(ePointEntity.getPPName().equals("杆塔") && ePointEntity.getPPWirenum()>=1) {
                String laxianWhere = " 1=1 and p_guid='" + pGuid + "' and p_p_guid='" + ePointEntity.getGuid() + "' and d_l_datastate !='删除' ";
                pointMap.put("filterSql", laxianWhere);
                laxList = eDrawLineService.queryList(pointMap);
                laxianList.addAll(laxList);
            }

            //交叉跨越
            pointMap.clear();
            String crossCostWhere = " 1=1 and c_c_upguid='"+ePointEntity.getGuid()+"' and c_c_datastate !='删除'";
            //台区选择
            if(LineArea != null && !LineArea.equals("")){
                crossCostWhere += " and p_r_guid='"+LineArea+"'";
            }
            pointMap.put("filterSql", crossCostWhere);
            dCrossList = eCrossCostService.queryList(pointMap);
            dCrossCostList.addAll(dCrossList);

        }

        //信息描述
        String pointInfo = getProInfoOnCad(pGuid,LineArea);

        //项目名称
        EPBaseEntity epBaseEntity = ePBaseService.queryObject(pGuid);
        String projectName = epBaseEntity.getPBName();

        //设计单位
        SysDeptEntity sysDeptEntity = sysDeptService.queryObject(epBaseEntity.getPBOrgid());
        String complanName = sysDeptEntity.getName();

        // 模板数据传递
        return R.ok().put("pointList",pointList)
                .put("laxianList",laxianList)
                .put("crossCostList",dCrossCostList)
                .put("textgcmc",projectName)
                .put("textsjdw",complanName)
                .put("projectName",projectName)
                .put("pointInfo",pointInfo);
    }



    /**
     *  list 去重
     *
     * @param list
     * @return
     */
    private static List<String> removeDuplicate(List<String> list) {
        LinkedHashSet<String> set = new LinkedHashSet<String>(list.size());
        set.addAll(list);
        list.clear();
        list.addAll(set);
        return list;
    }


    /**
     * 去掉末尾顿号
     * @param str
     * @return
     */
    public String removeDunhao(String str){
        if(str!=null && !str.equals("")){
            if(str.lastIndexOf("、") == str.length()-1){
                str = str.substring(0,str.length()-1);
            }
        }
        return str;
    }

}
